<?php
/*******************************************************************************
 * LightPress - http://lightpress.org
 *
 * Copyright 2004-2005 Ludovico Magnocavallo.
 * Released under the GPL http://www.gnu.org/copyleft/gpl.html
 *
 * $Id: sitemap.php 441 2006-06-25 13:58:11Z ludo $
 ******************************************************************************/

require_once 'config.php';

$f =& new Frontend($db_options, $options, null, 'sitemap'); // cache does not support feeds yet

$db =& $f->db;
$tpl =& $f->tpl;
$messages =& $f->messages;

if (isset($_GET['sitemap'])) {
    $sitemap_index = false;
    $feed_file = 'sitemap.xml';
} else {
    $sitemap_index = true;
    $feed_file = 'sitemap_index.xml';
}

$feed_date = "Y-m-d\TH:i:s";	// ISO 8601 format - could use "c" in PHP5...
$num_posts = (empty($f->context['type']) ? $options['posts_per_rss'] : 10000);

// Get GMT timestamp of last post modification

$tstamp = $f->getLastModified(false);

// ugh, send a content-type even if it should not be needed for 304s
// http://support.microsoft.com/default.aspx?scid=kb;en-us;831140&Product=ISAS

// we seem to be doing it right: http://www.xml.com/pub/a/2004/07/21/dive.html
header("Content-type: text/xml; charset=UTF-8", true);

$last_modified = $f->doConditionalGet($tstamp);

$posts =& $f->getPosts(null, null, 0, $num_posts, false, true);

$tpl->setFile('index', $feed_file);
$tpl->setVar('pub_date', $last_modified);

// are we building a google sitemap?
$items = array();
    
$month_days = array(31,28,31,30,31,30,31,31,30,31,31,31); // don't care about leap years

// add this context and any special children
switch ($f->context['type']) {
    
    case 'category':
        // Frontend has already fetched categories to check the context, so this is inexpensive
        $categories =& $f->getCategories();
        $category = $categories[$f->context['filter']];
        // but we still have to get the last modified date for the category
        $q = "select
                unix_timestamp(max(p.post_date_gmt)) as lastmod
              from
                {$f->tables['post2cat']} p2c
              inner join
                {$f->tables['posts']} p on p2c.post_id = p.id
              where
                p2c.category_id = {$category['cat_id']} and
                p.post_status = 'publish' and
                p.post_date_gmt < '{$f->where_date}'";
        if (!$f->db->query($q))
            $lastmod = time() - $f->options['gmt_offset']; // does not take into account GMT, but we have no posts so who cares
        else
            $lastmod = (int)$f->db->get('lastmod');
        
        $items[] = array(
            'location'      => $f->context['url'],
            'lastmod'       => $f->ISO8601($lastmod),
            'changefreq'    => 'weekly',
            'priority'      => '0.5');
        break;
        
    case 'archives':
        // Frontend has already fetched archives to check the context, so this is inexpensive
        $current_archive =& $f->context['filter'];
        $archives =& $f->getArchives();
        $archive =& $archives[$current_archive];
        if ($current_archive == date('Ym')) {
            $archive_lastmod = $posts[0]['post_tstamp_gmt'];
            $archive_changefreq = 'daily';
        } else {
            $archive_lastmod = $archive['date'] + $month_days[$archive['month'] - 1];
            $archive_changefreq = 'never';
        }
        $items[] = array(
            'location'      => $f->context['url'],
            'lastmod'       => $f->ISO8601($archive_lastmod),
            'changefreq'    => $archive_changefreq,
            'priority'      => '0.5');
        break;
            
    case 'search':
        // add when/if we have user-defined search results for sitemap
        break;
            
    case 'author':
        // add when/if we have user pages for sitemap
        break;
            
    default:
            
        // home page sitemap or sitemap index
            
        // add home page
        $items[] = array(
            'location'      => $options['url'] . '/' . ($sitemap_index ? 'sitemap.xml' : ''),
            'lastmod'       => $f->ISO8601($tstamp),
            'changefreq'    => 'daily',
            'priority'      => '1');
        
        // get last modified timestamps
        $q = "select
                p2c.category_id,
                unix_timestamp(max(p.post_date_gmt)) as lastmod
              from
                {$f->tables['post2cat']} p2c
              inner join
                {$f->tables['posts']} p on p2c.post_id = p.id
              where
                p.post_status = 'publish' and
                p.post_date_gmt < '{$f->where_date}'
              group by
                p2c.category_id";
        $f->db->query($q);
        $categories_lastmod = $f->db->all_assoc('category_id');
        // output categories
        foreach ($f->getCategories() as $cat_id=>$cat) {
            $items[] = array(
                'location'      => $options['url'] . '/' . $options['category_prefix'] . '/' . $cat['category_nicename'] . '/' . ($sitemap_index ? 'sitemap.xml' : ''),
                'lastmod'       => isset($categories_lastmod[$cat['cat_id']]) ? $f->ISO8601((int)$categories_lastmod[$cat['cat_id']]['lastmod']) : $f->ISO8601(time()  - $f->options['gmt_offset']),
                'changefreq'    => 'weekly',
                'priority'      => '0.5');
        }
        // output archives
        $current_archive = date('Ym');
            
        foreach ($f->getArchives() as $k=>$v) {
            // get last post date if it's the current month, build a fictional one otherwise
            if ($k == $current_archive) {
                $archive_lastmod = $f->ISO8601($tstamp);
                $archive_changefreq = 'daily';
            } else {
                $archive_lastmod = sprintf(
                    '%s-%s-%sT23:59:59+00:00',
                    $v['y'], $v['m'], $month_days[$v['month'] - 1]);
                $archive_changefreq = 'never';
            }
            $items[] = array(
                'location'      => $options['url'] . '/' . $v['permalink'] . '/' . ($sitemap_index ? 'sitemap.xml' : ''),
                'lastmod'       => $archive_lastmod,
                'changefreq'    => $archive_changefreq,
                'priority'      => '0.5');
        }

        // could also output user-defined search results URLs and author pages here
}
    
// add posts
if (!$sitemap_index) {
    foreach ($posts as $k => $post) {
        $items[] = array(
            'location'      => $options['url'] . '/' . $post['post_permalink'],
            'lastmod'       => $f->ISO8601((int)$post['post_tstamp_gmt']),
            'changefreq'    => (($post['comment_status'] == 'open' || $post['ping_status'] == 'open') ? 'daily' : 'never'),
            'priority'      => '1');
    }
}

$tpl->parseBlock('ITEM', 'item', $items, 'index');
    
$tpl->pparse('MAIN', 'index');

?>